"use strict";

import {
  config,
  dbData,
  main,
  rss,
  utils
} from "./app/instances";

// scene、cut、service。scene 的action会在被打断后压栈，cut的action会在被打断后直接结束，service会在后台执行，但没有任何界面。该字段在技能创建时被确定，无法由cloud app更改。

let handlers = {
  "ROKID.INTENT.WELCOME": holder => {
    return new Promise((resolve, reject) => {
      main.addTtsStr(config.tpls.welcome);
      holder.setBaseInfo({
        type: 'NORMAL',
        form: 'scene',
        shouldEndSession: false
      });
      holder.setTts({
        tts: main.getTtsStr()
      });
      holder.setPickup({
        enable: true,
        durationInMilliseconds: 6000,
        retryTts: "请重试"
      });
      resolve(":done");
    });
  },
  "rss.help": holder => {
    return new Promise((resolve, reject) => {
      main.addTtsStr(config.tpls.help);
      holder.setTts({
        tts: main.getTtsStr()
      });
      resolve(":done");
    });
  },
  // 模式选择
  "rss.config.mode": holder => {
    let mode = Rokid.param.request.content.slots.mode;
    return new Promise((resolve, reject) => {
      dbData.set("session", "rss.config.mode", mode);
      main.addTtsStr(
        config.tpls.configModel.format({
          mode
        })
      );
      holder.setTts({
        tts: main.getTtsStr()
      });
      resolve(":done");
    });
  },
  // 频道选择
  "rss.channel.go": holder => {
    let channel = Rokid.param.request.content.slots.channel;
    dbData.set("session", "channel", channel);
    dbData.set("session", "offset", 0);
    rss.setChannel(channel);
    return rss.fetch().then(result => {
      return new Promise((resolve, reject) => {
        if (rss._items.length > 0) {
          main.setTtsStr(channel + "一共有" + rss._items.length + "条记录");
        } else {
          main.setTtsStr("暂未在" + channel + "查询到更多记录。");
        }
        dbData.set("session", "rss_items", rss._items);
        holder.setBaseInfo({
          type: 'NORMAL',
          form: 'scene',
          shouldEndSession: false
        });
        holder.setTts({
          tts: main.getTtsStr()
        });
        resolve(":done");
      });
    });
  },
  // 翻页
  "rss.pager": holder => {
    let direction = Rokid.param.request.content.slots.direction;
    let offset = Rokid.param.request.content.slots.offset;
    try {
      offset = JSON.parse(offset).number;
    } catch (error) {
      offset - 1;
    }
    offset = Math.ceil(offset);
    let channel = dbData.get('session', "channel");
    let page = dbData.get('session', "page");
    if (isNaN(page) || page < 1) page = 1;
    page = rss.getPageNo(page, offset, direction);
    rss.setChannel(channel);
    dbData.set("session", "page", page);
    return rss.fetch().then(result => {
      return new Promise((resolve, reject) => {
        if (page <= 0) {
          main.setTtsStr("已经到最开始位置了，请浏览下一页！");
        } else {
          let result = rss.pager(page);
          if (result.hasOwnProperty("items") && result.items.length > 0) {
            main.setTtsStr(rss.ssml(result.items));
          } else {
            main.setTtsStr("暂未查询到更多记录。");
          }
        }
        holder.setTts({
          tts: main.getTtsStr()
        });
        resolve(":done");
      });
    });
  },
  // 播放
  "rss.play": holder => {
    return dbData.reload('session').then(session => {
      console.debug('----rss.play------');
      let channel = Rokid.param.request.content.slots.channel;
      if (!channel) {
        channel = dbData.get('session', 'channel');
      }
      let offset = dbData.get('session', "offset", 0);
      rss._items = dbData.get('session', "rss_items", []);
      if (rss._items.length > 0) {
        if (rss._items[offset] !== undefined) {
          main.setTtsStr(rss._items[offset].title);
          dbData.set("session", "offset", ++offset);
        } else {
          main.setTtsStr("暂未在" + channel + "查询到更多记录。");
        }
      }
      holder.setBaseInfo({
        type: 'NORMAL',
        form: 'scene',
        shouldEndSession: false
      });
      holder.setTts({
        tts: main.getTtsStr()
      });
      return ':done';
    });
    // return new Promise((resolve, reject) => {
    //   let channel = Rokid.param.request.content.slots.channel;
    //   if (!channel) {
    //     channel = dbData.get('session', 'channel');
    //   }
    //   let offset = dbData.get('session', "offset", 0);
    //   rss._items = dbData.get('session', "rss_items", []);
    //   if (rss._items.length > 0) {
    //     if (rss._items[offset] !== undefined) {
    //       main.setTtsStr(rss._items[offset].title);
    //       dbData.set("session", "offset", ++offset);
    //     } else {
    //       main.setTtsStr("暂未在" + channel + "查询到更多记录。");
    //     }
    //   }
    //   holder.setTts({
    //     tts: main.getTtsStr()
    //   });
    //   resolve(":done");
    // });
  },
  "Voice.STARTED": holder => {
    return new Promise((resolve, reject) => {
      resolve("rss.play");
    });
  },
  "Media.PAUSED": holder => {
    return new Promise((resolve, reject) => {
      resolve("rss.play");
    });
  },
  "Voice.FINISHED": holder => {
    return new Promise((resolve, reject) => {
      resolve("rss.play");
    });
  },
  "ROKID.INTENT.EXIT": holder => {
    return new Promise((resolve, reject) => {
      holder.setTts({
        tts: config.tpls.existSkillOK
      });
      resolve(":done");
    });
  }
};

// 响应事件注册
exports.handler = function (event, context, callback) {
  main.init(event, context, callback);
  main.registerHandlers(handlers);
  main.execute();
};
